package chaoyue.study.safe;

import java.util.Random;

/**
 * ThreadLocal在主线程和子线程之间的数据也是不通的
 * 如果需要主线程和子线程之间数据互通，需要使用 InheritableThreadLocal
 */
public class ThreadLocalTest3 {
    private static ThreadLocal<Integer> t1 = new ThreadLocal<>();
    private static InheritableThreadLocal<Integer> t2 = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        Random random = new Random();
        int value = random.nextInt(10000);
        // 主线程放入值
        t1.set(value);
        t2.set(value);
        System.out.println(Thread.currentThread().getName() + "放入值，值为 : " + value);
        Thread thread = new Thread(() -> {
            // 子线程取值
            System.out.println(Thread.currentThread().getName() + "进行取值(ThreadLocal)，值为 : " + t1.get());
            System.out.println(Thread.currentThread().getName() + "进行取值(InheritableThreadLocal)，值为 : " + t2.get());
        });
        thread.setName("thread-1");
        thread.start();
        System.out.println(Thread.currentThread().getName() + "进行取值(ThreadLocal)，值为 : " + t1.get());
        System.out.println(Thread.currentThread().getName() + "进行取值(InheritableThreadLocal)，值为 : " + t2.get());
    }
}
